// client/components/TorrentListItem.js (modification suggestion)
import React from "react";
import styled from "styled-components";
import Link from "next/link";
import Text from "./Text";
import Box from "./Box";

const Card = styled.div`
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  transition: box-shadow 0.2s;
  &:hover {
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.16);
  }
`;
const Cover = styled.img`
  width: 100%;
  height: 180px;
  object-fit: cover;
  background: #f5f5f5;
`;
const Info = styled.div`
  padding: 18px 16px 14px 16px;
  display: flex;
  flex-direction: column;
  flex: 1;
`;

const TorrentListItem = ({ torrent, categories, token, mode }) => {
  // 获取分类名
  const category =
    Object.keys(categories).find(
      (c) => c.toLowerCase() === (torrent.type || "").toLowerCase()
    ) ||
    torrent.type ||
    "-";

  // 判断图片格式
  function isPngImage(data) {
    if (!data) return false;
    // 只判断base64前几个字节
    return data.startsWith("iVBORw0KGgo");
  }

  // alert(torrent.poster);

  return (
    <Card>
      {torrent.poster ? (
        <Cover
          as="img"
          src={`data:image/${
            isPngImage(torrent.poster) ? "png" : "jpeg"
          };base64,${torrent.poster}`}
          alt={torrent.name}
        />
      ) : (
        <Cover
          as="div"
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            color: "#bbb",
            fontSize: 32,
          }}
        >
          无封面
        </Cover>
      )}
      <Info>
        <Link href={`/torrent/${torrent.infoHash}`} passHref>
          <Text
            as="a"
            fontWeight="bold"
            fontSize={2}
            mb={2}
            style={{ textDecoration: "none" }}
          >
            {torrent.name}
          </Text>
        </Link>
        <Text color="grey" fontSize={1} mb={2}>
          {category}
        </Text>
        <Box display="flex" flexWrap="wrap" alignItems="center" mb={2}>
          <Text fontSize={0} mr={3}>
            上传: {torrent.seeders !== undefined ? torrent.seeders : 0}
          </Text>
          <Text fontSize={0} mr={3}>
            下载: {torrent.leechers !== undefined ? torrent.leechers : 0}
          </Text>
          <Text fontSize={0} mr={3}>
            评论: {torrent.comments?.count ?? 0}
          </Text>
          <Text fontSize={0} mr={3}>
            评分: {torrent.scoreStats?.overallScore ? torrent.scoreStats.overallScore.toFixed(1) : "-"}
          </Text>
        </Box>
        <Text fontSize={0} color="grey">
          {torrent.created
            ? new Date(torrent.created).toLocaleDateString()
            : "-"}
        </Text>
      </Info>
    </Card>
  );
};

export default TorrentListItem;
